import { list, del, clear } from '@/api/initApi'

const queryParams = {
  pageNum: 1,
  pageSize: 10,
  orderByColumn: 'create_time',
  isAsc: 'desc'
}

export default {
  data() {
    return {
      // Dialog弹框的标题
      title: '',
      // 类别
      modalName: '',
      // 是否加载table数据中
      loading: false,
      // table数据
      list: [],
      // 总行数
      total: 0,
      // 表格中是否选中了单个，是则为true
      single: true,
      // 表格中是否选中了多个，是则为true
      multiple: true,
      // 选中行的id数组
      ids: [],
      // 选中行的数据
      row: {},
      dialogVisible: false,
      form: {},
      // 用来存放add/edit表单的初始化数据
      formReset: {},
      // url前缀
      base: '',
      // 查询参数，与具体组件合并后用来条件查询
      queryParams: { ...queryParams },
      dateRange: []
    }
  },
  methods: {
    init() {
      console.log(queryParams)
      this.queryParams = { ...queryParams }
      console.log(this.queryParams)
    },
    handleQuery(page) {
      this.beforeInit()
      if (page !== undefined) {
        if (page === 'reset') {
          this.init()
        } else if (page === '1') {
          this.queryParams.pageNum = 1
        }
      }
      this.loading = true
      list(this.base, this.addDateRange(this.queryParams, this.dateRange))
        .then(res => {
          this.total = res.total
          this.list = res.data
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSelectionChange(selection) {
      this.row = Object.assign({}, selection[0]) // 复制一个对象，解决编辑时，外层table数据一起变化的bug
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 新增按钮
    handleAdd() {
      this.reset()
      this.title = '新增' + this.modalName
      this.form = this.formReset
      this.dialogVisible = true
    },
    // 清空addForm
    reset() {
      this.$nextTick(() => {
        if(this.$refs['edit'] !== undefined) {
          this.form = this.formReset
        }
      })
    },
    // 修改按钮
    handleUpdate(row) {
      this.form = row || this.row
      this.dialogVisible = true
      this.title = '修改' + this.modalName
    },
    // 点击删除按钮
    handleDelete(id) {
      const ids = id || this.ids
      console.log(ids)
      this.$confirm('是否删除数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(this.base, ids)
          .then(() => {
            this.msgSuccess('删除成功')
            this.list = this.list.filter(v => !ids.includes(v.id))
            this.ids = []
          })
      })
    },
    // 表单提交
    submitForm() {
      this.$refs['edit'].submitForm()
    },
    // 表单取消按钮
    cancel() {
      this.dialogVisible = false
    }
  }
}
